package com.kwan.xframe.mvvm.data.source.http.converter;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.MalformedJsonException;
import com.kwan.xframe.mvvm.data.source.http.IHttpResult;
import com.kwan.xframe.mvvm.data.source.http.exception.HttpApiException;
import com.kwan.xframe.mvvm.data.source.http.exception.TokenExpireException;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import timber.log.Timber;

public class XGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

	private final Gson gson;
	private final TypeAdapter<T> adapter;


	XGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
		this.gson = gson;
		this.adapter = adapter;
	}

	@Override
	public T convert(ResponseBody value) throws IOException {

		JsonReader jsonReader = gson.newJsonReader(value.charStream());

		try {

			T result = adapter.read(jsonReader);

			Timber.e("convert:%s", result);

			if (result instanceof IHttpResult) {
				Timber.e("convert IHttpResult");
				
				if (((IHttpResult<?>) result).getTokenExpireCode()
						== ((IHttpResult<?>) result).getCode()) {
					TokenExpireException ex = new TokenExpireException("token已失效");
					ex.setCode(((IHttpResult<?>) result).getCode());
					throw ex;
				}
				
				if(!((IHttpResult<?>) result).isSuccess()){
					HttpApiException ex = new HttpApiException(((IHttpResult<?>) result).getMessage());
					ex.setCode(((IHttpResult<?>) result).getCode());
					throw ex;
				}

			}

			if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
				throw new JsonIOException("JSON document was not fully consumed.");
			}

			return result;

		} catch (MalformedJsonException e) {
			return null;
		} finally {
			value.close();
		}

	}
}
